package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @version v1.0
 * @date 2019/10/11 15:16
 * @description TODO
 **/
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        if (orderSettings != null && orderSettings.size() > 0) {
            //检查此数据是否存在
            for (OrderSetting orderSetting : orderSettings) {
                //检查数据中某个日期是否已经设置了
                long count=orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (count > 0) {
                    //已设置就更新
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    //未设置就添加
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }


    @Override
    public List<Map> findByMonth(String data) {
        String starDate = data + "-1";
        String endDate = data + "-31";

        Map<String, String> queryParam = new HashMap<>();
        queryParam.put("starDate", starDate);
        queryParam.put("endDate", endDate);

        //查询预约数据
        List<OrderSetting> settings=orderSettingDao.findByMonth(queryParam);

        //封装页面需要的页面结构
        List<Map> result = new ArrayList<>();

//        { date: 8, number: 120, reservations: 1 }
        if (settings != null&&settings.size()>0) {
            for (OrderSetting setting : settings) {
                Map<String, Integer> item = new HashMap<>();
                item.put("date", setting.getOrderDate().getDate());
                item.put("number", setting.getNumber());
                item.put("reservations", setting.getReservations());

                result.add(item);
            }
        }
        return result;

    }


    @Override
    public void settingByDay(OrderSetting orderSetting) {
        //预定日期是否有数据

        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0) {
            //已经设置了预约，更新数据
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            //没有设置预约，新增数据
            orderSettingDao.add(orderSetting);
        }
    }
}